/**
 * Placeholder Manager - 占位符内容管理系统
 * 基于 AI Writer Lite 的实现，为 IntelliMark 提供灵活的AI内容插入和管理
 */

export interface Placeholder {
  id: string
  type: 'ai_generated' | 'user_input' | 'template' | 'reference'
  content: string
  originalText?: string
  position: {
    start: number
    end: number
  }
  metadata: {
    operation?: string
    provider?: string
    model?: string
    timestamp: number
    confidence?: number
    tokensUsed?: number
    cost?: number
    context?: string
    status: 'pending' | 'completed' | 'failed' | 'replaced'
  }
}

export interface PlaceholderPattern {
  name: string
  pattern: RegExp
  description: string
  extractData?: (match: RegExpMatchArray) => any
}

export interface ContentInsertionOptions {
  preserveFormatting?: boolean
  mergeWithExisting?: boolean
  validateContext?: boolean
  autoReplace?: boolean
  customPatterns?: PlaceholderPattern[]
}

export interface InsertionResult {
  success: boolean
  content: string
  placeholders: Placeholder[]
  insertedPlaceholders: Placeholder[]
  errors: string[]
  warnings: string[]
  statistics: {
    totalPlaceholders: number
    insertedPlaceholders: number
    replacedPlaceholders: number
    pendingPlaceholders: number
  }
}

export class PlaceholderManager {
  private patterns: Map<string, PlaceholderPattern> = new Map()
  private placeholders: Map<string, Placeholder[]> = new Map() // documentId -> placeholders

  constructor() {
    this.initializeDefaultPatterns()
  }

  /**
   * 初始化默认占位符模式
   */
  private initializeDefaultPatterns(): void {
    // AI生成内容占位符
    this.addPattern({
      name: 'ai_content',
      pattern: /\[AI-CONTENT:([a-zA-Z0-9-]+)\]/g,
      description: 'AI生成内容占位符',
      extractData: (match) => ({ placeholderId: match[1] })
    })

    // 用户输入占位符
    this.addPattern({
      name: 'user_input',
      plot: /\[INPUT:([a-zA-Z0-9-]+):(.+?)\]/g,
      description: '用户输入占位符',
      extractData: (match) => ({
        placeholderId: match[1],
        prompt: match[2]
      })
    })

    // 模板占位符
    this.addPattern({
      name: 'template',
      pattern: /\[TEMPLATE:([a-zA-Z0-9-]+)\]/g,
      description: '模板占位符',
      extractData: (match) => ({ templateId: match[1] })
    })

    // 引用占位符
    this.addPattern({
      name: 'reference',
      pattern: /\[REF:([a-zA-Z0-9-]+)\]/g,
      description: '引用占位符',
      extractData: (match) => ({ referenceId: match[1] })
    })

    // 临时占位符
    this.addPattern({
      name: 'temp',
      pattern: /__TEMP_([A-Z0-9]+)__/g,
      description: '临时占位符',
      extractData: (match) => ({ tempId: match[1] })
    })
  }

  /**
   * 添加占位符模式
   */
  public addPattern(pattern: PlaceholderPattern): void {
    this.patterns.set(pattern.name, pattern)
  }

  /**
   * 插入AI生成内容
   */
  public insertAIContent(
    documentId: string,
    content: string,
    aiGeneratedText: string,
    position?: { start: number; end: number },
    options: ContentInsertionOptions = {}
  ): InsertionResult {
    const result: InsertionResult = {
      success: false,
      content,
      placeholders: [],
      insertedPlaceholders: [],
      errors: [],
      warnings: [],
      statistics: {
        totalPlaceholders: 0,
        insertedPlaceholders: 0,
        replacedPlaceholders: 0,
        pendingPlaceholders: 0
      }
    }

    try {
      // 创建占位符
      const placeholder: Placeholder = this.createPlaceholder(
        'ai_generated',
        aiGeneratedText,
        position || { start: content.length, end: content.length },
        {
          operation: 'ai_insertion',
          status: 'completed'
        }
      )

      // 生成占位符标记
      const placeholderTag = `[AI-CONTENT:${placeholder.id}]`

      // 插入占位符
      let newContent = content
      if (position) {
        newContent = content.substring(0, position.start) +
                    placeholderTag +
                    content.substring(position.end)
      } else {
        newContent = content + placeholderTag
      }

      // 保存占位符
      this.savePlaceholder(documentId, placeholder)

      result.success = true
      result.content = newContent
      result.insertedPlaceholders.push(placeholder)
      result.placeholders.push(placeholder)

      // 更新统计
      result.statistics.totalPlaceholders = 1
      result.statistics.insertedPlaceholders = 1

    } catch (error) {
      result.errors.push(`插入AI内容失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }

    return result
  }

  /**
   * 处理内容中的占位符
   */
  public processPlaceholders(
    documentId: string,
    content: string,
    options: ContentInsertionOptions = {}
  ): InsertionResult {
    const result: InsertionResult = {
      success: false,
      content,
      placeholders: [],
      insertedPlaceholders: [],
      errors: [],
      warnings: [],
      statistics: {
        totalPlaceholders: 0,
        insertedPlaceholders: 0,
        replacedPlaceholders: 0,
        pendingPlaceholders: 0
      }
    }

    try {
      let processedContent = content
      const foundPlaceholders: Placeholder[] = []
      const replacedPlaceholders: Placeholder[] = []

      // 获取文档的现有占位符
      const documentPlaceholders = this.getPlaceholders(documentId)

      // 处理每种占位符模式
      for (const [patternName, pattern] of this.patterns) {
        const matches = Array.from(content.matchAll(pattern.pattern))

        for (const match of matches) {
          const placeholder = this.extractPlaceholderFromMatch(
            pattern,
            match,
            documentId,
            content
          )

          if (placeholder) {
            foundPlaceholders.push(placeholder)
            result.statistics.totalPlaceholders++

            // 如果是已完成的占位符，替换内容
            if (placeholder.metadata.status === 'completed' && placeholder.content) {
              const replacement = options.preserveFormatting
                ? this.preserveFormatting(match[0], placeholder.content)
                : placeholder.content

              processedContent = processedContent.replace(match[0], replacement)
              replacedPlaceholders.push(placeholder)
              result.statistics.replacedPlaceholders++
            } else {
              result.statistics.pendingPlaceholders++
            }
          }
        }
      }

      // 添加自定义模式处理
      if (options.customPatterns) {
        for (const customPattern of options.customPatterns) {
          const matches = Array.from(content.matchAll(customPattern.pattern))
          // 处理自定义占位符...
        }
      }

      result.success = true
      result.content = processedContent
      result.placeholders = foundPlaceholders
      result.placeholders.push(...replacedPlaceholders)

    } catch (error) {
      result.errors.push(`处理占位符失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }

    return result
  }

  /**
   * 替换占位符
   */
  public replacePlaceholder(
    documentId: string,
    placeholderId: string,
    newContent: string,
    options: {
      preservePlaceholder?: boolean
      updateStatus?: boolean
    } = {}
  ): {
    success: boolean
    content?: string
    error?: string
  } {
    try {
      const placeholders = this.getPlaceholders(documentId)
      const placeholder = placeholders.find(p => p.id === placeholderId)

      if (!placeholder) {
        return {
          success: false,
          error: `占位符 ${placeholderId} 不存在`
        }
      }

      // 更新占位符内容
      placeholder.content = newContent
      placeholder.metadata.status = 'completed'
      placeholder.metadata.timestamp = Date.now()

      // 保存更新的占位符
      this.savePlaceholder(documentId, placeholder)

      return {
        success: true
      }

    } catch (error) {
      return {
        success: false,
        error: `替换占位符失败: ${error instanceof Error ? error.message : '未知错误'}`
      }
    }
  }

  /**
   * 删除占位符
   */
  public removePlaceholder(
    documentId: string,
    placeholderId: string
  ): {
    success: boolean
    error?: string
  } {
    try {
      const placeholders = this.getPlaceholders(documentId)
      const index = placeholders.findIndex(p => p.id === placeholderId)

      if (index === -1) {
        return {
          success: false,
          error: `占位符 ${placeholderId} 不存在`
        }
      }

      placeholders.splice(index, 1)
      this.savePlaceholders(documentId, placeholders)

      return {
        success: true
      }

    } catch (error) {
      return {
        success: false,
        error: `删除占位符失败: ${error instanceof Error ? error.message : '未知错误'}`
      }
    }
  }

  /**
   * 获取文档的所有占位符
   */
  public getPlaceholders(documentId: string): Placeholder[] {
    return this.placeholders.get(documentId) || []
  }

  /**
   * 获取特定类型的占位符
   */
  public getPlaceholdersByType(documentId: string, type: Placeholder['type']): Placeholder[] {
    return this.getPlaceholders(documentId).filter(p => p.type === type)
  }

  /**
   * 获取待处理的占位符
   */
  public getPendingPlaceholders(documentId: string): Placeholder[] {
    return this.getPlaceholders(documentId).filter(p => p.metadata.status === 'pending')
  }

  /**
   * 清理内容中的占位符标记
   */
  public cleanPlaceholders(
    content: string,
    options: {
      removePending?: boolean
      replaceCompleted?: boolean
    } = {}
  ): string {
    let cleanedContent = content

    // 清理所有占位符模式
    for (const pattern of this.patterns.values()) {
      cleanedContent = cleanedContent.replace(pattern.pattern, '')
    }

    return cleanedContent
  }

  /**
   * 验证占位符
   */
  public validatePlaceholders(documentId: string): {
    valid: boolean
    issues: Array<{
      placeholderId: string
      type: 'missing_content' | 'invalid_position' | 'corrupted_data'
      message: string
    }>
  } {
    const placeholders = this.getPlaceholders(documentId)
    const issues: Array<{
      placeholderId: string
      type: 'missing_content' | 'invalid_position' | 'corrupted_data'
      message: string
    }> = []

    placeholders.forEach(placeholder => {
      // 检查内容缺失
      if (!placeholder.content && placeholder.metadata.status === 'completed') {
        issues.push({
          placeholderId: placeholder.id,
          type: 'missing_content',
          message: '已完成状态但缺少内容'
        })
      }

      // 检查位置有效性
      if (placeholder.position.start < 0 || placeholder.position.end < placeholder.position.start) {
        issues.push({
          placeholderId: placeholder.id,
          type: 'invalid_position',
          message: '无效的位置信息'
        })
      }
    })

    return {
      valid: issues.length === 0,
      issues
    }
  }

  /**
   * 获取统计信息
   */
  public getStatistics(documentId?: string): {
    totalPlaceholders: number
    placeholdersByType: Record<string, number>
    placeholdersByStatus: Record<string, number>
    totalTokensUsed: number
    totalCost: number
  } {
    const allPlaceholders = documentId
      ? this.getPlaceholders(documentId)
      : Array.from(this.placeholders.values()).flat()

    const stats = {
      totalPlaceholders: allPlaceholders.length,
      placeholdersByType: {} as Record<string, number>,
      placeholdersByStatus: {} as Record<string, number>,
      totalTokensUsed: 0,
      totalCost: 0
    }

    allPlaceholders.forEach(placeholder => {
      // 按类型统计
      stats.placeholdersByType[placeholder.type] =
        (stats.placeholdersByType[placeholder.type] || 0) + 1

      // 按状态统计
      stats.placeholdersByStatus[placeholder.metadata.status] =
        (stats.placeholdersByStatus[placeholder.metadata.status] || 0) + 1

      // 统计资源使用
      if (placeholder.metadata.tokensUsed) {
        stats.totalTokensUsed += placeholder.metadata.tokensUsed
      }
      if (placeholder.metadata.cost) {
        stats.totalCost += placeholder.metadata.cost
      }
    })

    return stats
  }

  /**
   * 清理旧占位符
   */
  public cleanupOldPlaceholders(
    documentId: string,
    maxAge: number = 7 * 24 * 60 * 60 * 1000 // 7天
  ): void {
    const placeholders = this.getPlaceholders(documentId)
    const now = Date.now()
    const validPlaceholders = placeholders.filter(
      p => now - p.metadata.timestamp <= maxAge || p.metadata.status !== 'completed'
    )

    this.savePlaceholders(documentId, validPlaceholders)
  }

  /**
   * 导出占位符
   */
  public exportPlaceholders(documentId: string): Placeholder[] {
    return this.getPlaceholders(documentId)
  }

  /**
   * 导入占位符
   */
  public importPlaceholders(documentId: string, placeholders: Placeholder[]): void {
    this.savePlaceholders(documentId, placeholders)
  }

  // 私有方法

  private createPlaceholder(
    type: Placeholder['type'],
    content: string,
    position: { start: number; end: number },
    metadata: Partial<Placeholder['metadata']>
  ): Placeholder {
    return {
      id: this.generatePlaceholderId(),
      type,
      content,
      position,
      metadata: {
        timestamp: Date.now(),
        status: 'pending',
        ...metadata
      }
    }
  }

  private extractPlaceholderFromMatch(
    pattern: PlaceholderPattern,
    match: RegExpMatchArray,
    documentId: string,
    content: string
  ): Placeholder | null {
    try {
      const data = pattern.extractData ? pattern.extractData(match) : {}
      const placeholderId = (data as any).placeholderId || this.generatePlaceholderId()

      // 查找已存在的占位符
      const existingPlaceholders = this.getPlaceholders(documentId)
      const existingPlaceholder = existingPlaceholders.find(p => p.id === placeholderId)

      if (existingPlaceholder) {
        return existingPlaceholder
      }

      // 创建新占位符
      const placeholder = this.createPlaceholder(
        this.getPlaceholderTypeFromPattern(pattern.name),
        '', // 内容将在后续填充
        {
          start: match.index || 0,
          end: (match.index || 0) + match[0].length
        },
        {
          ...data,
          status: 'pending'
        }
      )

      return placeholder

    } catch (error) {
      console.error('提取占位符失败:', error)
      return null
    }
  }

  private getPlaceholderTypeFromPattern(patternName: string): Placeholder['type'] {
    const typeMap: Record<string, Placeholder['type']> = {
      'ai_content': 'ai_generated',
      'user_input': 'user_input',
      'template': 'template',
      'reference': 'reference',
      'temp': 'ai_generated'
    }

    return typeMap[patternName] || 'ai_generated'
  }

  private preserveFormatting(placeholderTag: string, content: string): string {
    // 简单的格式保留
    const beforeMatch = placeholderTag.match(/^[\s\t]*/)
    const afterMatch = placeholderTag.match(/[\s\t]*$/)

    const prefix = beforeMatch ? beforeMatch[0] : ''
    const suffix = afterMatch ? afterMatch[0] : ''

    return prefix + content.trim() + suffix
  }

  private generatePlaceholderId(): string {
    return `ph_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  private savePlaceholder(documentId: string, placeholder: Placeholder): void {
    const placeholders = this.getPlaceholders(documentId)

    // 查找并替换或添加新占位符
    const existingIndex = placeholders.findIndex(p => p.id === placeholder.id)
    if (existingIndex >= 0) {
      placeholders[existingIndex] = placeholder
    } else {
      placeholders.push(placeholder)
    }

    this.savePlaceholders(documentId, placeholders)
  }

  private savePlaceholders(documentId: string, placeholders: Placeholder[]): void {
    this.placeholders.set(documentId, [...placeholders])
  }
}

// 导出单例实例
let placeholderManagerInstance: PlaceholderManager | null = null

export function getPlaceholderManager(): PlaceholderManager {
  if (!placeholderManagerInstance) {
    placeholderManagerInstance = new PlaceholderManager()
  }
  return placeholderManagerInstance
}